package io.qifan.desktop.client.views.connect;

import io.qifan.desktop.api.protocol.request.ConnectReqMsg;
import io.qifan.desktop.client.event.Events;
import io.qifan.desktop.client.store.device.DeviceStore;
import io.qifan.desktop.client.views.BaseController;
import javafx.event.ActionEvent;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import java.net.URL;
import java.util.ResourceBundle;

@Component
@Slf4j
public class ConnectController implements BaseController, Initializable {
    public Label localDeviceId;
    public Label password;

    public TextField remotePassword;

    public TextField remoteDeviceId;

    public Button connectBtn;

    @Autowired
    ApplicationEventPublisher eventPublisher;

    @Override
    public void initialize(URL location, ResourceBundle resources) {

    }

    public void connect(ActionEvent actionEvent) {
        ConnectReqMsg reqMsg = new ConnectReqMsg();
        reqMsg.setLocalDeviceId(DeviceStore.currentDevice.getId());
        reqMsg.setRemoteDeviceId(Long.valueOf(remoteDeviceId.getText()));
        reqMsg.setPassword(remotePassword.getText());
        eventPublisher.publishEvent(new Events.SendConnectEvent(reqMsg));
    }


    @EventListener(Events.LoginSuccessEvent.class)
    public void handleLoginSuccessForConnectPanel() {
        localDeviceId.setText(String.valueOf(DeviceStore.currentDevice.getId()));
        password.setText(DeviceStore.currentDevice.getPassword());
    }
}
